//
//  WebDViewController.m
//  智云网校
//
//  Created by Damon on 2017/6/7.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "WebDViewController.h"
#import <WebKit/WebKit.h>

@interface WebDViewController ()<WKUIDelegate,UIDocumentInteractionControllerDelegate>
{
    UIDocumentInteractionController *documentController;
}
@property(nonatomic, strong)WKWebView *kWebView;

@property (strong, nonatomic) UIProgressView *progressView;



@end

@implementation WebDViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = self.titleName;
//    self.view.backgroundColor = [UIColor redColor];
    //    [self loadHeadView:@"" showBackBtn:YES];
    [self.view addSubview:self.kWebView];
    
    _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, CGRectGetWidth(self.view.frame),5)];
    [self.view addSubview:_progressView];
    _progressView.trackTintColor = [UIColor whiteColor];//底部
    _progressView.progressTintColor= MainThemeColor;//进度
    
    [self.kWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    
    [self.kWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

}
-(void)setUrlString:(NSString *)urlString{
    _urlString = urlString;
    NSLog(@"url:%@",urlString);
    if([urlString rangeOfString:@"http://"].location !=NSNotFound){//远程
        NSURL *url = [NSURL URLWithString:urlString];
        [self.kWebView loadRequest:[NSURLRequest requestWithURL:url]];
//        [self loadHeadView:@""];
    }else if([urlString rangeOfString:@"https://"].location !=NSNotFound){
        //远程
        NSURL *url = [NSURL URLWithString:urlString];
        [self.kWebView loadRequest:[NSURLRequest requestWithURL:url]];
//        [self loadHeadView:@""];
    }else{//本地
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:urlString]) {
            NSLog(@"文件存在");
        }else {
            NSLog(@"文件不存在");
        }

        NSData *data = [NSData dataWithContentsOfFile:urlString];
        if (data) {
            [self.kWebView loadData:data MIMEType:[self getMIMEType:urlString] characterEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:NSTemporaryDirectory()]];
        }else {
            NSURL *url = [NSURL fileURLWithPath:urlString];
            [self.kWebView loadRequest:[NSURLRequest requestWithURL:url]];
        }
//        [self loadHeadView:@"" addRightBtn:YES rightImageName:@"" rightTitle:@"分享"];

    }
}
- (NSString *)getMIMEType:(NSString *)urlString{
    NSArray *arr = [urlString componentsSeparatedByString:@"."];
    NSString *last = arr.lastObject;
    if ([last isEqualToString:@"doc"] || [last isEqualToString:@"dot"] || [last isEqualToString:@"docx"]) {
        return @"application/msword";
        
    }else if ([last isEqualToString:@"xls"] || [last isEqualToString:@"xlsx"]) {
        return @"application/vnd.ms-excel";

    }else if ([last isEqualToString:@"ppt"]) {
        return @"application/vnd.ms-powerpoint";

    }else if ([last isEqualToString:@"pdf"]) {
        return @"application/pdf";

    }else if ([last isEqualToString:@"html"]) {
        return @"text/html";

    }else if ([last isEqualToString:@"txt"]) {
        return @"text/plain";
    }else{
        return @"text/html";
    }
}
- (WKWebView *)kWebView{
    if (!_kWebView) {
        _kWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, screenWidth, ScreenHeight- kNavigationBarHeight)];
//        _kWebView.backgroundColor = [UIColor yellowColor];
        _kWebView.UIDelegate = self;
    }
    return _kWebView;
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    NSLog(@"--- %s ----",__func__);
}

//支持横屏
- (BOOL)shouldAutorotate {
    return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight | UIInterfaceOrientationPortrait |
    UIInterfaceOrientationPortraitUpsideDown  | UIInterfaceOrientationLandscapeLeft;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@" %s,change = %@",__FUNCTION__,change);
    if ([keyPath isEqual: @"estimatedProgress"] && object == self.kWebView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.kWebView.estimatedProgress animated:YES];
        if(self.kWebView.estimatedProgress >= 1.0f)
        {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }else if ([keyPath isEqualToString:@"title"])
    {
        if (object == self.kWebView) {
//            [self setHNavigationTitle:self.kWebView.title];

        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)dealloc {
    [self.kWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.kWebView removeObserver:self forKeyPath:@"title"];
    [self.kWebView setNavigationDelegate:nil];
    [self.kWebView setUIDelegate:nil];
}
#pragma mark 分享
- (void)headRightAction{
    if ([SettingObject objectIsValid:self.urlString]) {
        documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:self.urlString ? : @""]];
        documentController.delegate = self;
        documentController.UTI = @"pdf.doc.dot.docx.xls.xlsx.ppt.html.txt";
        [documentController presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];

    }else{
        [MBProgressHUD showTextOnly:self.view message:@"失败"];
    }
}

- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
    return self;
}
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    
    return self.view.frame;
}
//点击预览窗口的“Done”(完成)按钮时调用

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)_controller
{
    
}
@end
